package com.cloud.tsp.service;

import com.cloud.tsp.config.MailConfig;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author 杨斌
 * 2025-02-2025-02-11
 */
@Service
@Slf4j
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailConfig mailConfig;

    @Async
    public void sendEmailAsync(String subject, String text, String fileName, byte[] fileBytes) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(mailConfig.getTo());
            helper.setFrom(mailConfig.getFrom());
            helper.setCc(mailConfig.getCc().toArray(new String[0]));
            helper.setSubject(subject);
            helper.setText(text);
            helper.addAttachment(fileName, new ByteArrayResource(fileBytes));

            mailSender.send(message);
            log.info("邮件发送成功，收件人: {}, 抄送人: {}", mailConfig.getTo(), mailConfig.getCc());
        } catch ( MessagingException e) {
            log.error("邮件发送失败", e);
        }
    }
}
